import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.Method.POST
import static groovyx.net.http.ContentType.TEXT
import static groovyx.net.http.ContentType.HTML

/**
 * 네이트 랭킹뉴스의 뉴스 순위를 파싱하고 저장하는 클래스
 * 
 * @author : TaeHo Kim (xissysnd@gmail.com)
 */
class RankInfo {
	String section
	Date dateCreated
	Date dateViewed = new Date()
	static hasMany = [ listOfArticleRank: ArticleRank, ]
		
    static mapping = {
		// dateCreated가 자동으로 갱신되는 것을 방지한다.
		autoTimestamp false
	}
	
	static constraints = {
    }
	
	String toString() {
		"랭킹 정보 ($section, $dateCreated)"
	}
	
	static def parseRankInfo(String section, String date) {
		def htmlNewsMain = new HTTPBuilder('http://news.nate.com').request(GET,TEXT) { 
			uri.path = '/rank/interest'
			uri.query = [ sc: section, date: date, ]
		}
        assert htmlNewsMain instanceof Reader // response data is buffered in-memory
        def slurper = new XmlSlurper(new org.ccil.cowan.tagsoup.Parser())
		def html = slurper.parse(htmlNewsMain)
		
		// 1위부터 5위까지 
		def articles = html.body.div.div.div.div.div.div.findAll{ it.@class == 'mduSubjectList f_clear' }	
		assert articles.list().size() == 5
		
		def rankInfo = new RankInfo()
		rankInfo.listOfArticleRank = []
		
		articles.list().each { article ->
			def articleRank = new ArticleRank() 
			articleRank.articleTitle = article.dl.dt.a.strong
			articleRank.articleId = new URL(article.dl.dt.a.@href.text()).getPath().replace('/view/', '')
			String rankString = article.dl.dt.em.text().trim()
			articleRank.rank = rankString[0..rankString.size() - 2] as int
			
			rankInfo.listOfArticleRank.add( articleRank )
		}
		
		// 6위부터 30위까지 
		def sessions = html.body.div.div.div.div.div.ul.findAll{ it.@class == 'mduSubject mduRankSubject' }
    	sessions.list().each { listOfArticle ->
    		listOfArticle.li.list().each { article ->
	    		def articleRank = new ArticleRank() 
				articleRank.articleTitle = article.a.text()
				articleRank.articleId = new URL(article.a.@href.text()).getPath().replace('/view/', '')
				String rankString = article.dl.dt.em.text().trim()
				articleRank.rank = rankString[0..rankString.size() - 2] as int
				
				rankInfo.listOfArticleRank.add( articleRank )
			}
		}
		
		rankInfo.section = section
		rankInfo.dateCreated = Date.parse('yyyyMMdd', date)
		
		return rankInfo
	}
}
